home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / kernel / lfs / lfsSeg.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-12-19  |  56.8 KB  |  1,995 lines

  1. /* 
  2.  * lfsSeg.c --
  3.  *
  4.  *    Handles the manipulation of LFS segments.
  5.  *
  6.  * Copyright 1989 Regents of the University of California
  7.  * Permission to use, copy, modify, and distribute this
  8.  * software and its documentation for any purpose and without
  9.  * fee is hereby granted, provided that the above copyright
  10.  * notice appear in all copies.  The University of California
  11.  * makes no representations about the suitability of this
  12.  * software for any purpose.  It is provided "as is" without
  13.  * express or implied warranty.
  14.  */
  15.  
  16. #ifndef lint
  17. static char rcsid[] = "$Header: /cdrom/src/kernel/Cvsroot/kernel/lfs/lfsSeg.c,v 1.25 92/08/11 16:37:27 mgbaker Exp $ SPRITE (Berkeley)";
  18. #endif /* not lint */
  19.  
  20. #include <lfsInt.h>
  21. #include <lfsSeg.h>
  22. #include <stdlib.h>
  23. #include <sync.h>
  24. #include <fsStat.h>
  25. #include <fsrecov.h>
  26. #include <recov.h>
  27.  
  28. #define    LOCKPTR    &lfsPtr->lock
  29.  
  30. int    lfsMinNumberToClean = 10;
  31.  
  32. Boolean    lfsSegWriteDebug = FALSE;
  33.  
  34. #define    MIN_SUMMARY_REGION_SIZE    16
  35.  
  36. #ifndef VERIFY_CLEAN
  37. enum CallBackType { SEG_LAYOUT, SEG_CLEAN_IN, SEG_CLEAN_OUT, SEG_CHECKPOINT, 
  38.            SEG_WRITEDONE};
  39. #else
  40. enum CallBackType { SEG_LAYOUT, SEG_CLEAN_IN, SEG_CLEAN_OUT, SEG_CHECKPOINT, 
  41.            SEG_WRITEDONE, SEG_CLEAN_VERIFY};
  42. #endif
  43.  
  44. LfsSegIoInterface *lfsSegIoInterfacePtrs[LFS_MAX_NUM_MODS];
  45.  
  46.  
  47. static void SegmentCleanProc _ARGS_((ClientData clientData, 
  48.                      Proc_CallInfo *callInfoPtr));
  49. static LfsSeg *CreateSegmentToClean _ARGS_((Lfs *lfsPtr, int segNumber, 
  50.             char *cleaningMemPtr));
  51. static LfsSeg *CreateSegmentToWrite _ARGS_((Lfs *lfsPtr, Boolean dontBlock));
  52. static LfsSeg *GetSegStruct _ARGS_((Lfs *lfsPtr, LfsSegLogRange 
  53.             *segLogRangePtr, int startBlockOffset, char *memPtr));
  54. static void AddNewSummaryBlock _ARGS_((LfsSeg *segPtr));
  55. static Boolean DoOutCallBacks _ARGS_((enum CallBackType type, LfsSeg *segPtr, int flags, char *checkPointPtr, int *sizePtr, ClientData *clientDataPtr));
  56. static ReturnStatus WriteSegmentStart _ARGS_((LfsSeg *segPtr));
  57. static ReturnStatus WriteSegmentFinish _ARGS_((LfsSeg *segPtr));
  58. static void WriteDoneNotify _ARGS_((Lfs *lfsPtr));
  59. static void RewindCurPtrs _ARGS_((LfsSeg *segPtr));
  60. static Boolean DoInCallBacks _ARGS_((enum CallBackType type, LfsSeg *segPtr, int flags, int *sizePtr, int *numCacheBlocksPtr, ClientData *clientDataPtr));
  61. static void DestorySegStruct _ARGS_((LfsSeg *segPtr));
  62.  
  63. /*
  64.  * Macro returning TRUE if segment is completely empty.
  65.  */
  66. #define SegIsEmpty(segPtr) (((segPtr)->numBlocks == 1) &&         \
  67.         ((segPtr)->curSegSummaryPtr->size == sizeof(LfsSegSummary)))
  68.  
  69. /*
  70.  *----------------------------------------------------------------------
  71.  *
  72.  * -- LfsSegIoRegister
  73.  *
  74.  *    Register with the segment module an interface to objects in the log.   
  75.  *
  76.  * Results:
  77.  *    None.
  78.  *
  79.  * Side effects:
  80.  *    None.
  81.  *
  82.  *----------------------------------------------------------------------
  83.  */
  84.  
  85. void
  86. LfsSegIoRegister(moduleType, ioInterfacePtr)
  87.     int            moduleType; /* Module type registering. Type defined in
  88.                      * lfsSegWrite.h */
  89.     LfsSegIoInterface    *ioInterfacePtr;  /* Interface to use. */
  90.  
  91. {
  92.     lfsSegIoInterfacePtrs[moduleType] = ioInterfacePtr;
  93. }
  94.  
  95. /*
  96.  *----------------------------------------------------------------------
  97.  *
  98.  * LfsSegmentWriteProc --
  99.  *
  100.  *    Proc_CallFunc procedure for performing a segment writes.
  101.  *
  102.  * Results:
  103.  *    None.
  104.  *
  105.  * Side effects:
  106.  *    None.
  107.  *
  108.  *----------------------------------------------------------------------
  109.  */
  110.  
  111. /*ARGSUSED*/
  112.  void
  113. LfsSegmentWriteProc(clientData, callInfoPtr)
  114.     ClientData       clientData;
  115.     Proc_CallInfo *callInfoPtr;         /* Not used. */
  116. {
  117.     register Lfs *lfsPtr;            /* File system with dirty blocks. */
  118.     Boolean    full;
  119.     LfsSeg    *segPtr;
  120.     ClientData        clientDataArray[LFS_MAX_NUM_MODS];
  121.     int            i;
  122.     ReturnStatus    status;
  123.     Boolean        moreWork;
  124.  
  125.  
  126.     lfsPtr = (Lfs *) clientData;
  127.     /*
  128.      * All the stuff with these FSYNC flags is for the ASPLOS measurements
  129.      * only.  It can all be removed after that's all over.  Mary  2/14/92.
  130.      */
  131.     lfsPtr->controlFlags &= ~LFS_FSYNC_IN_PROGRESS;
  132.     moreWork = TRUE;
  133.     if (lfsPtr->controlFlags & LFS_FILE_FSYNCED) {
  134.     lfsPtr->controlFlags &= ~LFS_FILE_FSYNCED;
  135.     lfsPtr->controlFlags |= LFS_FSYNC_IN_PROGRESS;
  136.     }
  137.     while (moreWork) { 
  138.     full = TRUE;
  139.     for (i = 0; i < LFS_MAX_NUM_MODS; i++) {
  140.         clientDataArray[i] = (ClientData) NIL;
  141.     }
  142.     while (full) {
  143.         segPtr = CreateSegmentToWrite(lfsPtr, FALSE);
  144.         full = DoOutCallBacks(SEG_LAYOUT, segPtr, 0, (char *) NIL,
  145.                     (int *) NIL, clientDataArray);
  146.         status = WriteSegmentStart(segPtr);
  147.         if (status == SUCCESS) {
  148.         status = WriteSegmentFinish(segPtr);
  149.         }
  150.         if (status != SUCCESS) {
  151.         LfsError(lfsPtr, status, "Can't write segment to log\n");
  152.         }
  153.         RewindCurPtrs(segPtr);
  154.         (void) DoInCallBacks(SEG_WRITEDONE, segPtr, 0,
  155.                     (int *) NIL, (int *) NIL, clientDataArray);
  156.         WriteDoneNotify(lfsPtr);
  157.         DestorySegStruct(segPtr);
  158.     }
  159.     moreWork = LfsMoreToWriteBack(lfsPtr);
  160.     if (lfsPtr->controlFlags & LFS_FILE_FSYNCED) {
  161.         lfsPtr->controlFlags &= ~LFS_FILE_FSYNCED;
  162.         lfsPtr->controlFlags |= LFS_FSYNC_IN_PROGRESS;
  163.     } else {
  164.         lfsPtr->controlFlags &= ~LFS_FSYNC_IN_PROGRESS;
  165.     }
  166.     }
  167.     return;
  168. }
  169.  
  170.  
  171. /*
  172.  *----------------------------------------------------------------------
  173.  *
  174.  * LfsSegCleanStart --
  175.  *
  176.  *    Request that the segment manager start cleaning segments
  177.  *    for the specified file system.
  178.  *
  179.  * Results:
  180.  *    None.
  181.  *
  182.  * Side effects:
  183.  *    A segment cleaning process may be started.
  184.  *
  185.  *----------------------------------------------------------------------
  186.  */
  187.  
  188. void
  189. LfsSegCleanStart(lfsPtr)
  190.     Lfs     *lfsPtr;    /* File system needing segments cleaned. */
  191. {
  192.     LFS_STATS_INC(lfsPtr->stats.cleaning.startRequests);
  193.     if (lfsPtr->activeFlags & LFS_CLEANER_ACTIVE) {
  194.     LFS_STATS_INC(lfsPtr->stats.cleaning.alreadyActive);
  195.     return;
  196.     }
  197.     lfsPtr->activeFlags |= LFS_CLEANER_ACTIVE;
  198.     Proc_CallFunc(SegmentCleanProc, (ClientData) lfsPtr, 0);
  199. }
  200.  
  201. /*
  202.  *----------------------------------------------------------------------
  203.  *
  204.  * LfsSegSlowGrowSummary --
  205.  *
  206.  *    Insure that there is enought room for an object with the 
  207.  *    specified number of blocks and summary bytes. Possibly add a
  208.  *    new summary block if needed.
  209.  *
  210.  * Results:
  211.  *    A pointer to the summary bytes for this region or NIL if
  212.  *    there is not enought room.
  213.  *
  214.  * Side effects:
  215.  *
  216.  *----------------------------------------------------------------------
  217.  */
  218.  
  219. char *
  220. LfsSegSlowGrowSummary(segPtr, dataBlocksNeeded, sumBytesNeeded, addNewBlock)
  221.     register LfsSeg    *segPtr;    /* Segment of interest. */
  222.     int     dataBlocksNeeded;        /* Number of data blocks needed. */
  223.     int    sumBytesNeeded;            /* Number of summary bytes needed. */
  224.     Boolean addNewBlock;        /* Added a new block if necessary. */
  225. {
  226.     int     sumBytesLeft, blocksLeft, sumBlocks;
  227.  
  228.     /*
  229.      * Test the most common case first. Do the data and summary fit
  230.      * in the current configuration. 
  231.      */
  232.     sumBytesLeft = LfsSegSummaryBytesLeft(segPtr);
  233.     blocksLeft = LfsSegBlocksLeft(segPtr);
  234.     if ((blocksLeft >= dataBlocksNeeded) && (sumBytesLeft >= sumBytesNeeded)) {
  235.        return segPtr->curSummaryPtr;
  236.     }
  237.     /*
  238.      * Need to add a summary block. Bail if the user doesn't what it 
  239.      * or there is not enought room.
  240.      */
  241.     sumBlocks = 1;
  242.     if (!addNewBlock || (dataBlocksNeeded + sumBlocks > blocksLeft)) { 
  243.     return (char *) NIL;
  244.     }
  245.     /*
  246.      * Malloc a new summary buffer and add it to the segment.
  247.      */
  248.     AddNewSummaryBlock(segPtr);
  249.     return segPtr->curSummaryPtr;
  250. }
  251.  
  252. /*
  253.  *----------------------------------------------------------------------
  254.  *
  255.  * LfsSegSlowDiskAddress --
  256.  *
  257.  *    Compute the disk address of a LfsSegElement.
  258.  *
  259.  * Results:
  260.  *    The disk address of the element.
  261.  *
  262.  * Side effects:
  263.  *    None.
  264.  *
  265.  *----------------------------------------------------------------------
  266.  */
  267.  
  268. LfsDiskAddr
  269. LfsSegSlowDiskAddress(segPtr, segElementPtr)
  270.     register LfsSeg    *segPtr;     /* Segment of interest. */
  271.     LfsSegElement *segElementPtr; /* Segment element of interest. */
  272. {
  273.     int    elementNumber, blockOffset;
  274.     LfsDiskAddr diskAddress, newDiskAddr;
  275.     /*
  276.      * Check the common case that we are asking about the "current"
  277.      * element. 
  278.      */
  279.     elementNumber = segElementPtr - segPtr->segElementPtr;
  280.  
  281.     if (elementNumber == segPtr->curElement) {
  282.     blockOffset = segPtr->curBlockOffset;
  283.     } else {
  284.     int    i;
  285.     blockOffset = segPtr->startBlockOffset;
  286.     for (i = 0; i <= elementNumber; i++) {
  287.         blockOffset += segPtr->segElementPtr[i].lengthInBlocks;
  288.     }
  289.     }
  290.     LfsSegNumToDiskAddress(segPtr->lfsPtr, segPtr->logRange.current, 
  291.         &diskAddress);
  292.     blockOffset = LfsSegSizeInBlocks(segPtr->lfsPtr) - blockOffset;
  293.     LfsDiskAddrPlusOffset(diskAddress, blockOffset, &newDiskAddr);
  294.     return newDiskAddr;
  295. }
  296.  
  297. /*
  298.  *----------------------------------------------------------------------
  299.  *
  300.  * LfsSegSlowAddDataBuffer --
  301.  *
  302.  *    Add a LfsSegElement to a segment.
  303.  *
  304.  * Results:
  305.  *    A pointer to the LfsSegElement added. NIL if the object would not
  306.  *    fit.
  307.  *
  308.  * Side effects:
  309.  *    None.
  310.  *
  311.  *----------------------------------------------------------------------
  312.  */
  313.  
  314. LfsSegElement *
  315. LfsSegSlowAddDataBuffer(segPtr, blocks, bufferPtr, clientData)
  316.     register LfsSeg    *segPtr;  /* Segment to add to. */ 
  317.     int            blocks;      /* Size of buffer to add in blocks */
  318.     char   *bufferPtr;      /* Buffer to add. */
  319.     ClientData clientData; /* ClientData associated with this field. */
  320. {
  321.     LfsSegElement *elementPtr;
  322.  
  323.     if (segPtr->curBlockOffset + blocks > segPtr->curDataBlockLimit) {
  324.     return (LfsSegElement *) NIL;
  325.     }
  326.     segPtr->curElement++;
  327.     segPtr->curBlockOffset += blocks;
  328.  
  329.     elementPtr = segPtr->segElementPtr + segPtr->curElement;
  330.     elementPtr->lengthInBlocks = blocks;
  331.     elementPtr->clientData = clientData;
  332.     elementPtr->address    = bufferPtr;
  333.     segPtr->numElements = segPtr->curElement+1;
  334.     segPtr->numBlocks += blocks;
  335.     return elementPtr;
  336. }
  337.  
  338. /*
  339.  *----------------------------------------------------------------------
  340.  *
  341.  * InitSegmentMem --
  342.  *
  343.  *    Initialize the memory used by a file systems segment code.
  344.  *
  345.  * Results:
  346.  *    None.
  347.  *
  348.  * Side effects:
  349.  *    LfsSeg memories allocated.
  350.  *
  351.  *----------------------------------------------------------------------
  352.  */
  353. void
  354. InitSegmentMem(lfsPtr)
  355.     Lfs    *lfsPtr;
  356. {
  357.     LfsSeg    *segPtr;
  358.     int        maxSegElementSize;
  359.     int        i;
  360.     DevBlockDeviceHandle *handlePtr;
  361.  
  362.     /*
  363.      * Compute the maximum size of the seg element array. It can't be
  364.      * bigger than one element per block in segment.
  365.      */
  366.  
  367.     maxSegElementSize = LfsBytesToBlocks(lfsPtr,LfsSegSize(lfsPtr)) * 
  368.                     sizeof(LfsSegElement);
  369.     /*
  370.      * Fill in the fixed fields of the preallocated segments.
  371.      */
  372.     lfsPtr->segsInUse = 0;
  373.     lfsPtr->segs = (LfsSeg *) malloc(LFS_NUM_PREALLOC_SEGS *sizeof(LfsSeg));
  374.     for (i = 0; i < LFS_NUM_PREALLOC_SEGS; i++) { 
  375.     segPtr = lfsPtr->segs + i;
  376.     segPtr->lfsPtr = lfsPtr;
  377.     segPtr->segElementPtr = (LfsSegElement *) malloc(maxSegElementSize);
  378.     }
  379.     handlePtr = (DevBlockDeviceHandle *) lfsPtr->devicePtr->data;
  380.     if (handlePtr->maxTransferSize < LfsSegSize(lfsPtr)) { 
  381.     lfsPtr->writeBuffers[0] = malloc(handlePtr->maxTransferSize*2);
  382.     lfsPtr->writeBuffers[1] = lfsPtr->writeBuffers[0] + 
  383.                     handlePtr->maxTransferSize;
  384.     } else {
  385.     lfsPtr->writeBuffers[0] = malloc(LfsSegSize(lfsPtr));
  386.     lfsPtr->writeBuffers[1] = (char *) NIL;
  387.     }
  388.  
  389. }
  390.  
  391. /*
  392.  *----------------------------------------------------------------------
  393.  *
  394.  * FreeSegmentMem --
  395.  *
  396.  *    Free the memory used by a file systems segment code.
  397.  *
  398.  * Results:
  399.  *    None.
  400.  *
  401.  * Side effects:
  402.  *    LfsSeg structures freed.
  403.  *
  404.  *----------------------------------------------------------------------
  405.  */
  406. void
  407. FreeSegmentMem(lfsPtr)
  408.     Lfs    *lfsPtr;
  409. {
  410.     int i;
  411.     free(lfsPtr->writeBuffers[0]);
  412.     lfsPtr->segsInUse = 0;
  413.     for (i = 0; i < LFS_NUM_PREALLOC_SEGS; i++) { 
  414.     free((char *)(lfsPtr->segs[i].segElementPtr));
  415.     }
  416.     free((char *) (lfsPtr->segs));
  417.  
  418. }
  419.  
  420. /*
  421.  *----------------------------------------------------------------------
  422.  *
  423.  * AddNewSummaryBlock --
  424.  *
  425.  *  Add a summary block to a segment.
  426.  *
  427.  * Results:
  428.  *    None.
  429.  *
  430.  * Side effects:
  431.  *    A new summary block is malloc() and initialized.
  432.  *
  433.  *----------------------------------------------------------------------
  434.  */
  435. static void
  436. AddNewSummaryBlock(segPtr)
  437.     LfsSeg    *segPtr;    /* Seg to add block to. */
  438. {
  439.     LfsSegElement *sumBufferPtr;
  440.     LfsSegSummary *newSummaryPtr;
  441.     int          sumBytes;
  442.  
  443.     sumBytes = LfsBlockSize(segPtr->lfsPtr);
  444.     sumBufferPtr = LfsSegAddDataBuffer(segPtr, 1, malloc(sumBytes),
  445.                     (ClientData) NIL);
  446.     newSummaryPtr =  (LfsSegSummary *) sumBufferPtr->address;
  447.     newSummaryPtr->magic = LFS_SEG_SUMMARY_MAGIC;
  448.     newSummaryPtr->timestamp = LfsGetCurrentTimestamp(segPtr->lfsPtr);
  449.     newSummaryPtr->prevSeg = segPtr->logRange.prevSeg;
  450.     newSummaryPtr->nextSeg = segPtr->logRange.nextSeg;
  451.     newSummaryPtr->size = sizeof(LfsSegSummary);
  452.     newSummaryPtr->nextSummaryBlock = -1;
  453.  
  454.     if (segPtr->curSegSummaryPtr != (LfsSegSummary *) NIL) { 
  455.     /*
  456.      * This is not the first summary block in the segment.  Fixup the
  457.      * size of the last summary block and point it at the new one. 
  458.      */
  459.     segPtr->curSegSummaryPtr->size = segPtr->curSummaryPtr - 
  460.                     (char *) (segPtr->curSegSummaryPtr);
  461.     segPtr->curSegSummaryPtr->nextSummaryBlock = segPtr->curBlockOffset;
  462.     } 
  463.     segPtr->curSegSummaryPtr = newSummaryPtr;
  464.  
  465.     segPtr->curSummaryPtr = sumBufferPtr->address + sizeof(LfsSegSummary);
  466.     segPtr->curSummaryLimitPtr = sumBufferPtr->address + sumBytes;
  467. }
  468.  
  469. void
  470. CopySegToBuffer( segPtr, maxSize, bufferPtr, lenPtr)
  471.     LfsSeg    *segPtr;
  472.     int        maxSize;
  473.     char    *bufferPtr;
  474.     int        *lenPtr;
  475. {
  476.     int bytes, offset;
  477.     LfsSegElement *elementPtr;
  478.     Boolean full;
  479.  
  480.     *lenPtr = 0;
  481.     offset = 0;
  482.     full = FALSE;
  483.     while ((segPtr->curElement >= 0) && !full) {
  484.     elementPtr = segPtr->segElementPtr + segPtr->curElement;
  485.     bytes = LfsBlocksToBytes(segPtr->lfsPtr, 
  486.         elementPtr->lengthInBlocks - segPtr->curBlockOffset);
  487.     if (*lenPtr + bytes > maxSize) {
  488.         /*
  489.          * Element doesn't fit in this buffer. 
  490.          */
  491.         if (*lenPtr == maxSize) {
  492.         offset = 0;
  493.         } else { 
  494.         offset = LfsBytesToBlocks(segPtr->lfsPtr,(maxSize - *lenPtr));
  495.         }
  496.         bytes = LfsBlocksToBytes(segPtr->lfsPtr, offset);
  497.         full = TRUE;
  498.     } 
  499.     if (segPtr->curBlockOffset == 0) { 
  500.         bcopy(elementPtr->address, bufferPtr + *lenPtr, bytes);
  501.     } else {
  502.         bcopy(elementPtr->address + 
  503.            LfsBlocksToBytes(segPtr->lfsPtr,segPtr->curBlockOffset),
  504.           bufferPtr + *lenPtr, bytes);
  505.     }
  506.     *lenPtr += bytes;
  507.     if (full) {
  508.         segPtr->curBlockOffset += offset;
  509.     } else {
  510.         segPtr->curElement--;
  511.         segPtr->curBlockOffset = 0;
  512.     }
  513.     }
  514. }
  515.  
  516.  
  517. /*
  518.  *----------------------------------------------------------------------
  519.  *
  520.  * SegIoDoneProc --
  521.  *
  522.  *    This procedure is called when a sync block command started by 
  523.  *    WriteSegmentStart finished. It's calling sequence is 
  524.  *    defined by the call back caused by the Dev_BlockDeviceIO routine.
  525.  *
  526.  * Results:
  527.  *    None.
  528.  *
  529.  * Side effects:
  530.  *
  531.  *----------------------------------------------------------------------
  532.  */
  533.  
  534. static void
  535. SegIoDoneProc(requestPtr, status, amountTransferred)
  536.     DevBlockDeviceRequest    *requestPtr;
  537.     ReturnStatus status;
  538.     int    amountTransferred;
  539. {
  540.     LfsSeg    *segPtr = (LfsSeg *) (requestPtr->clientData);
  541.     DevBlockDeviceHandle *handlePtr;
  542.  
  543.     handlePtr = (DevBlockDeviceHandle *) segPtr->lfsPtr->devicePtr->data;
  544.     /*
  545.      * A pointer to the LfsSeg is passed as the clientData to this call.
  546.      * Start the new request if one is available. If this is the last
  547.      * request note the I/O as done.
  548.      */
  549.     MASTER_LOCK(&segPtr->ioMutex);
  550.     if (amountTransferred != requestPtr->bufferLen) {
  551.     status = VM_SHORT_WRITE;
  552.     }
  553.     if (status != SUCCESS) {
  554.     segPtr->ioReturnStatus = status;
  555.     }
  556.     requestPtr->startAddress = DEV_BYTES_PER_SECTOR * 
  557.                 LfsDiskAddrToOffset(segPtr->nextDiskAddress);
  558.     requestPtr->bufferLen = 0;
  559.     CopySegToBuffer(segPtr, handlePtr->maxTransferSize, requestPtr->buffer, 
  560.             &requestPtr->bufferLen);
  561.     segPtr->nextDiskAddress += requestPtr->bufferLen/DEV_BYTES_PER_SECTOR;
  562.     if (requestPtr->bufferLen == 0) { 
  563.     segPtr->requestActive--;
  564.     if (segPtr->requestActive == 0) {
  565.         segPtr->ioDone = TRUE;
  566.         Sync_MasterBroadcast(&segPtr->ioDoneWait);
  567.     }
  568.     } 
  569.     MASTER_UNLOCK(&segPtr->ioMutex);
  570.     if (requestPtr->bufferLen > 0) {
  571.     status = Dev_BlockDeviceIO(handlePtr, requestPtr);
  572.     if (status != SUCCESS) {
  573.         LfsError(segPtr->lfsPtr, status, "Can't start log write.\n");
  574.     }
  575.     }
  576.     return;
  577. }
  578.  
  579.  
  580. /*
  581.  *----------------------------------------------------------------------
  582.  *
  583.  * WriteSegmentStart --
  584.  *
  585.  *    Start a segment write to the log.
  586.  *
  587.  * Results:
  588.  *    SUCCESS if write complete. The ReturnStatus otherwise.
  589.  *
  590.  * Side effects:
  591.  *    None.
  592.  *
  593.  *----------------------------------------------------------------------
  594.  */
  595. static ReturnStatus
  596. WriteSegmentStart(segPtr) 
  597.     LfsSeg    *segPtr;    /* Segment to write. */
  598. {
  599.     Lfs    *lfsPtr = segPtr->lfsPtr;
  600.     int offset;
  601.     LfsDiskAddr  diskAddress;
  602.     ReturnStatus status = SUCCESS;
  603.     DevBlockDeviceHandle *handlePtr;
  604.     DevBlockDeviceRequest *requestPtr;
  605.  
  606.     Sync_SemInitDynamic(&(segPtr->ioMutex),"LfsSegIoMutex");
  607.     segPtr->ioDone = FALSE;
  608.     segPtr->ioReturnStatus = SUCCESS;
  609.  
  610.     if (SegIsEmpty(segPtr)) { 
  611.     /*
  612.      * The segment being written is empty so we don't have
  613.      * to write anytime. Just mark the I/O as done.
  614.      */
  615.     segPtr->ioDone = TRUE;
  616.     return SUCCESS;
  617.     }
  618.  
  619.     handlePtr = (DevBlockDeviceHandle *) lfsPtr->devicePtr->data;
  620.  
  621.     /*
  622.      * Writing to a segment nukes the segment cache.
  623.      */
  624.     if (lfsPtr->segCache.valid && 
  625.      (lfsPtr->segCache.segNum == segPtr->logRange.current)) {
  626.     lfsPtr->segCache.valid = FALSE;
  627.     }
  628.     LFS_STATS_INC(lfsPtr->stats.log.segWrites);
  629.     /*
  630.      * This flag is for the ASPLOS paper.  Remove when that's all over.
  631.      *             Mary 2/15/92.
  632.      */
  633.     if ((lfsPtr->controlFlags & LFS_FSYNC_IN_PROGRESS) && Lfs_DoASPLOSStats) {
  634.     LFS_STATS_INC(lfsPtr->stats.log.fsyncWrites);
  635.     }
  636.  
  637.     LFS_STATS_ADD(lfsPtr->stats.log.wasteBlocks,
  638.                 segPtr->curDataBlockLimit - segPtr->curBlockOffset);
  639.     /*
  640.      * Compute the starting disk address of this I/O.
  641.      */
  642.     LfsSegNumToDiskAddress(lfsPtr, segPtr->logRange.current, &diskAddress);
  643.     offset = LfsSegSizeInBlocks(lfsPtr)    - segPtr->curBlockOffset;
  644.     LfsDiskAddrPlusOffset(diskAddress,offset, &segPtr->nextDiskAddress);
  645.  
  646.  
  647.     /*
  648.      * Fill in the request block fields that don't change between 
  649.      * requests.
  650.      */
  651.  
  652.     segPtr->bioreq[0].operation = segPtr->bioreq[1].operation = FS_WRITE;
  653.     segPtr->bioreq[0].startAddrHigh = segPtr->bioreq[1].startAddrHigh = 0;
  654.     segPtr->bioreq[0].doneProc = segPtr->bioreq[1].doneProc = SegIoDoneProc;
  655.     segPtr->bioreq[0].clientData = segPtr->bioreq[1].clientData = 
  656.                 (ClientData) segPtr;
  657.  
  658.     segPtr->curElement = segPtr->numElements-1;
  659.     segPtr->curBlockOffset = 0;
  660.     /*
  661.      * Start up the first two disk I/Os. 
  662.      */
  663.     requestPtr = segPtr->bioreq+0;
  664.     requestPtr->startAddress = DEV_BYTES_PER_SECTOR * 
  665.                 LfsDiskAddrToOffset(segPtr->nextDiskAddress);
  666.     requestPtr->buffer = lfsPtr->writeBuffers[0];
  667.     requestPtr->bufferLen = 0;
  668.     CopySegToBuffer(segPtr, handlePtr->maxTransferSize, requestPtr->buffer,
  669.         &requestPtr->bufferLen);
  670.     segPtr->nextDiskAddress += requestPtr->bufferLen/DEV_BYTES_PER_SECTOR;
  671.     segPtr->requestActive = 1;
  672.  
  673.     /*
  674.      * Disk request number 2.
  675.      */
  676.     requestPtr = segPtr->bioreq+1;
  677.     requestPtr->startAddress = DEV_BYTES_PER_SECTOR * 
  678.                 LfsDiskAddrToOffset(segPtr->nextDiskAddress);
  679.     requestPtr->buffer = lfsPtr->writeBuffers[1];
  680.     requestPtr->bufferLen = 0;
  681.     CopySegToBuffer(segPtr, handlePtr->maxTransferSize, requestPtr->buffer,
  682.             &requestPtr->bufferLen);
  683.     segPtr->nextDiskAddress += requestPtr->bufferLen/DEV_BYTES_PER_SECTOR;
  684.     if (requestPtr->bufferLen > 0) { 
  685.     segPtr->requestActive = 2;
  686.     } else {
  687.     segPtr->requestActive = 1;
  688.     }
  689.     status = Dev_BlockDeviceIO(handlePtr, segPtr->bioreq);
  690.     if (status != SUCCESS) {
  691.     LfsError(lfsPtr, status, "Can't start disk log write.\n");
  692.     }
  693.     if (requestPtr->bufferLen > 0) {
  694.     status = Dev_BlockDeviceIO(handlePtr, segPtr->bioreq+1);
  695.     if (status != SUCCESS) {
  696.         LfsError(lfsPtr, status, "Can't start disk log write.\n");
  697.     }
  698.     }
  699.  
  700.  
  701.     LFS_STATS_ADD(lfsPtr->stats.log.blocksWritten, segPtr->numBlocks);
  702.     LFS_STATS_ADD(lfsPtr->stats.log.bytesWritten, segPtr->activeBytes);
  703.     /*
  704.      * This flag is for the ASPLOS paper.  Remove when that's all over.
  705.      *             Mary 2/15/92.
  706.      */
  707.     if ((lfsPtr->controlFlags & LFS_FSYNC_IN_PROGRESS) && Lfs_DoASPLOSStats) {
  708.     LFS_STATS_ADD(lfsPtr->stats.log.fsyncBytes, segPtr->activeBytes);
  709.     }
  710.     return status;
  711. }
  712.  
  713. /*
  714.  *----------------------------------------------------------------------
  715.  *
  716.  * WriteSegmentFinish --
  717.  *
  718.  *    Wait for a segment write to finish.
  719.  *
  720.  * Results:
  721.  *    SUCCESS if write complete. The ReturnStatus otherwise.
  722.  *
  723.  * Side effects:
  724.  *    None.
  725.  *
  726.  *----------------------------------------------------------------------
  727.  */
  728. static ReturnStatus
  729. WriteSegmentFinish(segPtr) 
  730.     LfsSeg    *segPtr;    /* Segment to wait for. */
  731. {
  732.     ReturnStatus status;
  733.     MASTER_LOCK((&segPtr->ioMutex));
  734.     while (segPtr->ioDone == FALSE) { 
  735.     Sync_MasterWait((&segPtr->ioDoneWait),(&segPtr->ioMutex),FALSE);
  736.     }
  737.     status = segPtr->ioReturnStatus;
  738.     MASTER_UNLOCK((&segPtr->ioMutex));
  739.  
  740.     return status;
  741. }
  742.  
  743.  
  744. /*
  745.  *----------------------------------------------------------------------
  746.  *
  747.  * WriteDoneNotify --
  748.  *
  749.  *    Notify others that a log write has finished and another may be
  750.  *    started.
  751.  *
  752.  * Results:
  753.  *    None
  754.  *
  755.  * Side effects:
  756.  *    None.
  757.  *
  758.  *----------------------------------------------------------------------
  759.  */
  760.  
  761. static void
  762. WriteDoneNotify(lfsPtr)
  763.     Lfs    *lfsPtr;
  764. {
  765.     LOCK_MONITOR;
  766.     lfsPtr->activeFlags &= ~LFS_WRITE_ACTIVE;
  767.     Sync_Broadcast(&lfsPtr->writeWait);
  768.     UNLOCK_MONITOR;
  769. }
  770.  
  771. /*
  772.  *----------------------------------------------------------------------
  773.  *
  774.  * CreateSegmentToWrite --
  775.  *
  776.  *    Create an LfsSeg structure describing an empty segment to be 
  777.  *    filled in by the callback routines.
  778.  *
  779.  * Results:
  780.  *    A pointer to a lfsSeg.
  781.  *
  782.  * Side effects:
  783.  *    None.
  784.  *
  785.  *----------------------------------------------------------------------
  786.  */
  787. static LfsSeg *
  788. CreateSegmentToWrite(lfsPtr, dontBlock) 
  789.     Lfs    *lfsPtr;        /* For which file system. */
  790.     Boolean        dontBlock;    /* Don't wait for segment. */
  791. {
  792.     LfsSeg    *segPtr;
  793.     LfsSegLogRange    segLogRange;
  794.     int        startBlock;
  795.     ReturnStatus status;
  796.  
  797.     LOCK_MONITOR;
  798.  
  799.     /*
  800.      * Wait for previous writes to finish.
  801.      */
  802.     while (lfsPtr->activeFlags & LFS_WRITE_ACTIVE) {
  803.     Sync_Wait(&lfsPtr->writeWait, FALSE);
  804.     }
  805.  
  806.     do { 
  807.     status = LfsGetLogTail(lfsPtr, dontBlock, &segLogRange, &startBlock);
  808.     if ((status == FS_WOULD_BLOCK) && !dontBlock) {
  809.         LFS_STATS_INC(lfsPtr->stats.log.cleanSegWait);
  810.         lfsPtr->activeFlags |= LFS_CLEANSEGWAIT_ACTIVE;
  811.         Sync_Wait(&lfsPtr->cleanSegmentsWait, FALSE);
  812.     } 
  813.     } while ((status == FS_WOULD_BLOCK) && !dontBlock);
  814.  
  815.     if (status == SUCCESS) { 
  816.     lfsPtr->activeFlags |= LFS_WRITE_ACTIVE;
  817.     segPtr = GetSegStruct(lfsPtr, &segLogRange, startBlock, (char *) NIL);
  818.     } else {
  819.     segPtr = (LfsSeg *) NIL;
  820.     }
  821.     UNLOCK_MONITOR;
  822.     return segPtr;
  823. }
  824.  
  825. /*
  826.  *----------------------------------------------------------------------
  827.  *
  828.  * RewindCurPtrs --
  829.  *
  830.  *    Rewind the current pointers of a segment to the start of the first
  831.  *    segment.
  832.  *
  833.  * Results:
  834.  *    None.
  835.  *
  836.  * Side effects:
  837.  *    None.
  838.  *
  839.  *----------------------------------------------------------------------
  840.  */
  841. static void
  842. RewindCurPtrs(segPtr)
  843.     LfsSeg    *segPtr;
  844. {
  845.     segPtr->curSegSummaryPtr = (LfsSegSummary *) 
  846.                 (segPtr->segElementPtr[0].address);
  847.     segPtr->curSummaryHdrPtr = (LfsSegSummaryHdr *) 
  848.                 (segPtr->curSegSummaryPtr + 1);
  849.     segPtr->curElement = 1;
  850.  
  851.     segPtr->curBlockOffset = segPtr->startBlockOffset+1;
  852.     segPtr->curDataBlockLimit = segPtr->curSummaryHdrPtr->numDataBlocks;
  853.     segPtr->curSummaryPtr = (char *) (segPtr->curSummaryHdrPtr + 1);
  854.     segPtr->curSummaryLimitPtr = (char *) (segPtr->curSummaryHdrPtr) +
  855.             segPtr->curSummaryHdrPtr->lengthInBytes;
  856.  
  857. }
  858.  
  859. /*
  860.  *----------------------------------------------------------------------
  861.  *
  862.  * DestorySegStruct --
  863.  *
  864.  *    Destory an LfsSeg structure.
  865.  *
  866.  * Results:
  867.  *    None.
  868.  *
  869.  * Side effects:
  870.  *    None.
  871.  *
  872.  *----------------------------------------------------------------------
  873.  */
  874.  
  875. static void
  876. DestorySegStruct(segPtr)
  877.     LfsSeg    *segPtr;    /* Segment to Destory. */
  878. {
  879.  
  880.     int num;
  881.  
  882.     num = segPtr - segPtr->lfsPtr->segs;
  883.     segPtr->lfsPtr->segsInUse  &= ~(1 << num);
  884. }
  885.  
  886.  
  887. /*
  888.  *----------------------------------------------------------------------
  889.  *
  890.  * GetSegStruct --
  891.  *
  892.  *    Allocate an LfsSeg structure.
  893.  *
  894.  * Results:
  895.  *    A lfsSeg structure
  896.  *
  897.  * Side effects:
  898.  *    None.
  899.  *
  900.  *----------------------------------------------------------------------
  901.  */
  902.  
  903. static LfsSeg *
  904. GetSegStruct(lfsPtr, segLogRangePtr, startBlockOffset, memPtr)
  905.     Lfs    *lfsPtr;    /* File system. */
  906.     LfsSegLogRange *segLogRangePtr; /* Log range of segment. */
  907.     int           startBlockOffset; /* Starting block offset into segment */
  908.     char       *memPtr;         /* Memory allocated for segment. */
  909. {
  910.     int        i;
  911.     LfsSeg    *segPtr;
  912.  
  913.     segPtr = (LfsSeg *) NIL;
  914.     for (i = 0; i < LFS_NUM_PREALLOC_SEGS; i++) { 
  915.     if (!(lfsPtr->segsInUse & (1 << i))) {
  916.         lfsPtr->segsInUse |= (1 << i);
  917.         segPtr = lfsPtr->segs + i;
  918.         break;
  919.     }
  920.     }
  921.     if (segPtr == (LfsSeg *) NIL) {
  922.     panic("GetSegStruct out of segment structures.\n");
  923.     }
  924.     segPtr->memPtr = memPtr;
  925.     segPtr->logRange = *segLogRangePtr;
  926.     segPtr->numElements = 0;
  927.     segPtr->numBlocks = 0;
  928.     segPtr->startBlockOffset = startBlockOffset;
  929.     segPtr->activeBytes = 0;
  930.     segPtr->timeOfLastWrite = 0;
  931.     segPtr->curSegSummaryPtr = (LfsSegSummary *) NIL;
  932.     segPtr->curSummaryHdrPtr = (LfsSegSummaryHdr *) NIL;
  933.     segPtr->curElement = -1;
  934.     segPtr->curBlockOffset = segPtr->startBlockOffset;
  935.     segPtr->curDataBlockLimit = LfsSegSizeInBlocks(lfsPtr);
  936.     segPtr->curSummaryPtr = (char *) NIL;
  937.     segPtr->curSummaryLimitPtr = (char *) NIL;
  938.  
  939.     return segPtr;
  940. }
  941.  
  942.  
  943. /*
  944.  *----------------------------------------------------------------------
  945.  *
  946.  * DoInCallBacks --
  947.  *
  948.  *    Perform the call backs that take segments as input.
  949.  *
  950.  * Results:
  951.  *    TRUE if the segment is full. False otherwise.
  952.  *
  953.  * Side effects:
  954.  *    None.
  955.  *
  956.  *----------------------------------------------------------------------
  957.  */
  958. static Boolean
  959. DoInCallBacks(type, segPtr, flags, sizePtr, numCacheBlocksPtr, clientDataPtr) 
  960.     enum CallBackType type;    /* Type of segment operation. */
  961.     LfsSeg    *segPtr;    /* Segment to fill in or out. */
  962.     int        flags;        /* Flags used during checkpoint. */
  963.     int            *sizePtr; /* Size of checkpoint buffer or segment cleaned. */
  964.     int *numCacheBlocksPtr;
  965.     ClientData *clientDataPtr;
  966.  
  967. {
  968.     int    moduleType, size, numCacheBlocks, next;
  969.     Boolean error = FALSE;
  970.     char     *endSummaryBlockPtr;
  971.     LfsSegElement *bufferPtr;
  972.  
  973.     /*
  974.      * We're doing a pass over an existing segment such as during a
  975.      * cleaning IN phase or a WRITE_DONE callback. Initialize the 
  976.      * moduleType from the summary region. 
  977.      */
  978.     endSummaryBlockPtr = (char *)segPtr->curSegSummaryPtr + 
  979.             segPtr->curSegSummaryPtr->size;
  980.     while(!error) { 
  981.     while (((char *)segPtr->curSummaryHdrPtr < endSummaryBlockPtr) &&
  982.             (segPtr->curSummaryHdrPtr->lengthInBytes > 0))  {
  983.         LfsSegIoInterface *intPtr;
  984.     
  985.         moduleType = segPtr->curSummaryHdrPtr->moduleType;
  986.         segPtr->curSummaryLimitPtr = ((char *)(segPtr->curSummaryHdrPtr) + 
  987.                 segPtr->curSummaryHdrPtr->lengthInBytes);
  988.         segPtr->curSummaryPtr = (char *) (segPtr->curSummaryHdrPtr + 1);
  989.         intPtr = lfsSegIoInterfacePtrs[moduleType];
  990.         switch (type) {
  991.         case SEG_CLEAN_IN:
  992.         size = 0;
  993.         numCacheBlocks = 0;
  994.         error = intPtr->clean(segPtr, &size, &numCacheBlocks, 
  995.                 clientDataPtr + moduleType);
  996. #ifdef lint
  997.         error = LfsDescMapClean(segPtr, &size, &numCacheBlocks, 
  998.                 clientDataPtr + moduleType);
  999.         error = LfsSegUsageClean(segPtr, &size, &numCacheBlocks, 
  1000.                 clientDataPtr + moduleType);
  1001.         error = LfsFileLayoutClean(segPtr, &size, &numCacheBlocks, 
  1002.                 clientDataPtr + moduleType);
  1003. #endif /* lint */
  1004.         *sizePtr += size;
  1005.         *numCacheBlocksPtr += numCacheBlocks;
  1006.         break;
  1007.         case SEG_WRITEDONE: {
  1008.         intPtr->writeDone(segPtr, flags, clientDataPtr + moduleType);
  1009. #ifdef lint
  1010.         LfsDescMapWriteDone(segPtr, flags,  clientDataPtr + moduleType);
  1011.         LfsSegUsageWriteDone(segPtr, flags, clientDataPtr + moduleType);
  1012.         LfsFileLayoutWriteDone(segPtr, flags, clientDataPtr + moduleType);
  1013. #endif /* lint */
  1014.         break;
  1015.          }
  1016. #ifdef VERIFY_CLEAN
  1017.          case SEG_CLEAN_VERIFY: {
  1018.          extern Boolean LfsFileLayoutCleanVerify 
  1019.              _ARGS_((LfsSeg *segPtr));
  1020.          if (moduleType == LFS_FILE_LAYOUT_MOD) {
  1021.              (void) LfsFileLayoutCleanVerify(segPtr);
  1022.          }
  1023.          break;
  1024.          }
  1025. #endif
  1026.          default:
  1027.          panic("lfsSeg.c: Bad case statement\n");
  1028.          }
  1029.          if (error) {
  1030.             break;
  1031.          }
  1032.          segPtr->curBlockOffset += segPtr->curSummaryHdrPtr->numDataBlocks;
  1033.          /*
  1034.           * Skip to the next summary header. 
  1035.           */
  1036.          segPtr->curSummaryHdrPtr = 
  1037.             (LfsSegSummaryHdr *) segPtr->curSummaryLimitPtr;
  1038.      }
  1039.      if (error) {
  1040.         break;
  1041.      }
  1042.      /*
  1043.       * If we ran over the end of current summary block move on to 
  1044.       * the next.
  1045.       */
  1046.       next = segPtr->curSegSummaryPtr->nextSummaryBlock;
  1047.       if (type == SEG_WRITEDONE) {
  1048.         /*
  1049.          * Free up any memory we allocated during the layout
  1050.          */
  1051.         LFS_STATS_ADD(segPtr->lfsPtr->stats.log.summaryBytesWritten,
  1052.                 segPtr->curSegSummaryPtr->size);
  1053.         LFS_STATS_INC(segPtr->lfsPtr->stats.log.summaryBlocksWritten);
  1054.         free((char *) segPtr->curSegSummaryPtr);
  1055.       }
  1056.           if (next == -1) {
  1057.         /*
  1058.          * No more summary bytes for this segment.
  1059.          */
  1060.         break;
  1061.        }
  1062.        bufferPtr = LfsSegGetBufferPtr(segPtr);
  1063.        segPtr->curSegSummaryPtr = (LfsSegSummary *) bufferPtr->address;
  1064.        segPtr->curSummaryHdrPtr = (LfsSegSummaryHdr *)
  1065.                         (segPtr->curSegSummaryPtr + 1);
  1066.        endSummaryBlockPtr = (char *)segPtr->curSegSummaryPtr + 
  1067.             segPtr->curSegSummaryPtr->size;
  1068.        bufferPtr++;
  1069.        LfsSegSetBufferPtr(segPtr, bufferPtr);
  1070.        segPtr->curBlockOffset = next;
  1071.     }
  1072.    return error;
  1073. }
  1074.  
  1075.  
  1076. /*
  1077.  *----------------------------------------------------------------------
  1078.  *
  1079.  * DoOutCallBacks --
  1080.  *
  1081.  *    Perform the call backs for output to segments.
  1082.  *
  1083.  * Results:
  1084.  *    TRUE if the segment is full. False otherwise.
  1085.  *
  1086.  * Side effects:
  1087.  *    None.
  1088.  *
  1089.  *----------------------------------------------------------------------
  1090.  */
  1091. static Boolean
  1092. DoOutCallBacks(type, segPtr, flags, checkPointPtr, sizePtr, clientDataPtr) 
  1093.     enum CallBackType type;    /* Type of segment operation. */
  1094.     LfsSeg    *segPtr;    /* Segment to fill in or out. */
  1095.     int        flags;        /* Flags used during checkpoint. */
  1096.     char    *checkPointPtr; /* Checkpoint buffer. */
  1097.     int            *sizePtr; /* Size of checkpoint buffer or segment cleaned. */
  1098.     ClientData *clientDataPtr;
  1099.  
  1100. {
  1101.     int    moduleType, startOffset;
  1102.     Boolean full;
  1103.     char    *summaryPtr, *endSummaryPtr;
  1104.     int        newStartBlockOffset;
  1105.     LfsCheckPointRegion    *segUsageCheckpointRegionPtr;
  1106.     unsigned int         firstActiveBytesLow;               /* For ASPLOS. */
  1107.     unsigned int         firstActiveBytesHigh;              /* For ASPLOS. */
  1108.  
  1109.  
  1110.     full = FALSE;
  1111.  
  1112.     /* Next stats for ASPLOS only.  Remove when done.  -Mary 2/15/92. */
  1113.     firstActiveBytesLow = segPtr->lfsPtr->stats.log.fileBytesWritten.low;
  1114.     firstActiveBytesHigh = segPtr->lfsPtr->stats.log.fileBytesWritten.high;
  1115.  
  1116.     segUsageCheckpointRegionPtr = (LfsCheckPointRegion *) NIL;
  1117.     for(moduleType = 0; moduleType < LFS_MAX_NUM_MODS; ) {
  1118.     LfsSegIoInterface *intPtr = lfsSegIoInterfacePtrs[moduleType];
  1119.     /*
  1120.      * Filling in a segment, be sure that there is enought
  1121.      * room for the LfsSegSummaryHdr.
  1122.      */
  1123.     summaryPtr = LfsSegSlowGrowSummary(segPtr, 1,
  1124.         sizeof(LfsSegSummaryHdr) + MIN_SUMMARY_REGION_SIZE, TRUE);
  1125.     if (summaryPtr == (char *) NIL) {
  1126.         full = TRUE;
  1127.         break;
  1128.     }
  1129.     segPtr->curSummaryHdrPtr = (LfsSegSummaryHdr *)  summaryPtr;
  1130.     LfsSegSetSummaryPtr(segPtr, summaryPtr + sizeof(LfsSegSummaryHdr));
  1131.     startOffset = segPtr->curBlockOffset;
  1132.     switch (type) {
  1133.     case SEG_CLEAN_OUT:
  1134.     case SEG_LAYOUT: 
  1135.         full = intPtr->layout(segPtr, flags, clientDataPtr + moduleType);
  1136. #ifdef lint
  1137.         full = LfsSegUsageLayout(segPtr, flags, clientDataPtr + moduleType);
  1138.         full = LfsDescMapLayout(segPtr, flags, clientDataPtr + moduleType);
  1139.         full = LfsFileLayoutProc(segPtr, flags, clientDataPtr + moduleType);
  1140. #endif /* lint */
  1141.         break;
  1142.     case SEG_CHECKPOINT: {
  1143.         int    size;
  1144.         LfsCheckPointRegion    *regionPtr;
  1145.         regionPtr = (LfsCheckPointRegion *) checkPointPtr;
  1146.         size = 0;
  1147.         full = intPtr->checkpoint(segPtr, flags, (char *)(regionPtr + 1),
  1148.                      &size, clientDataPtr + moduleType);
  1149. #ifdef lint
  1150.         full = LfsDescMapCheckpoint(segPtr, flags, (char *)(regionPtr + 1),
  1151.                      &size, clientDataPtr + moduleType);
  1152.         full = LfsSegUsageCheckpoint(segPtr, flags, (char *)(regionPtr + 1),
  1153.                      &size, clientDataPtr + moduleType);
  1154.         full = LfsFileLayoutCheckpoint(segPtr, flags,
  1155.                 (char *)(regionPtr + 1), &size,
  1156.                 clientDataPtr + moduleType);
  1157. #endif /* lint */
  1158.         if (size > 0) {
  1159.         if (moduleType == LFS_SEG_USAGE_MOD) {
  1160.             segUsageCheckpointRegionPtr = regionPtr;
  1161.         }
  1162.         regionPtr->type = moduleType;
  1163.         regionPtr->size = size + sizeof(LfsCheckPointRegion);
  1164.         *sizePtr += regionPtr->size;
  1165.         checkPointPtr += regionPtr->size;
  1166.         }
  1167.         break;
  1168.      }
  1169.      default:
  1170.          panic("lfsSeg.c: Bad case statement\n");
  1171.      }
  1172.      /*
  1173.       * If the callback added data to the segment, fill in the summary 
  1174.       * header. 
  1175.       */
  1176.      endSummaryPtr = LfsSegGetSummaryPtr(segPtr); 
  1177.      if ((startOffset != segPtr->curBlockOffset) ||
  1178.          ((summaryPtr + sizeof(LfsSegSummaryHdr)) != endSummaryPtr)) {
  1179.         segPtr->curSummaryHdrPtr->moduleType = moduleType;
  1180.         segPtr->curSummaryHdrPtr->lengthInBytes = endSummaryPtr - 
  1181.                 (char *) summaryPtr;
  1182.         segPtr->curSummaryHdrPtr->numDataBlocks =  
  1183.                 segPtr->curBlockOffset - startOffset;
  1184.      } else {
  1185.          LfsSegSetSummaryPtr(segPtr, summaryPtr);
  1186.      }
  1187.      /*
  1188.       * If we didn't fill the segment in skip to the next module.
  1189.       */
  1190.      if (full) { 
  1191.         if (LfsSegSummaryBytesLeft(segPtr) > MIN_SUMMARY_REGION_SIZE) {
  1192.         break;
  1193.         }
  1194.      } else {
  1195.         moduleType++;
  1196.      }
  1197.    }
  1198.    /*
  1199.     * Update the size of the last summary block and cap off this segment. 
  1200.     */
  1201.    segPtr->curSegSummaryPtr->size = segPtr->curSummaryPtr - 
  1202.                     (char *) segPtr->curSegSummaryPtr;
  1203.  
  1204.    newStartBlockOffset = -1;
  1205.    if (!full) {
  1206.     if (SegIsEmpty(segPtr)) { 
  1207.         /*
  1208.          * The segment is totally empty.  We don't need to write
  1209.          * this one yet.
  1210.          */
  1211.         LFS_STATS_INC(segPtr->lfsPtr->stats.log.emptyWrites);
  1212.         newStartBlockOffset = segPtr->startBlockOffset;
  1213.     } else if ((segPtr->curDataBlockLimit -  segPtr->curBlockOffset) > 
  1214.                segPtr->lfsPtr->superBlock.usageArray.wasteBlocks) { 
  1215.         /*
  1216.          * If this is considered to be a partial segment write add the
  1217.          * summary block we needed.
  1218.          */
  1219.         AddNewSummaryBlock(segPtr);
  1220.         newStartBlockOffset = segPtr->curBlockOffset-1;
  1221.         LFS_STATS_INC(segPtr->lfsPtr->stats.log.partialWrites);
  1222.         /*
  1223.          * These stats are for the ASPLOS paper.  Remove when that's all
  1224.          * over.               Mary 2/15/92.
  1225.          */
  1226.         if ((segPtr->lfsPtr->controlFlags & LFS_FSYNC_IN_PROGRESS) &&
  1227.             Lfs_DoASPLOSStats) {
  1228.         LFS_STATS_INC(segPtr->lfsPtr->stats.log.fsyncPartialWrites);
  1229.         LFS_STATS_ADD(segPtr->lfsPtr->stats.log.fsyncPartialBytes,
  1230.             segPtr->activeBytes);
  1231.         }
  1232.         if (Lfs_DoASPLOSStats) {
  1233.         LFS_STATS_ADD(segPtr->lfsPtr->stats.log.partialWriteBytes,
  1234.             segPtr->activeBytes);
  1235.         if (type == SEG_CLEAN_OUT) {
  1236.             LFS_STATS_ADD(
  1237.                 segPtr->lfsPtr->stats.log.cleanPartialWriteBytes,
  1238.                 segPtr->activeBytes);
  1239.         }
  1240.         if (segPtr->lfsPtr->stats.log.fileBytesWritten.low -
  1241.             firstActiveBytesLow < firstActiveBytesLow) {
  1242.             int    addit;
  1243.  
  1244.             addit = segPtr->lfsPtr->stats.log.fileBytesWritten.low -
  1245.                 firstActiveBytesLow;
  1246.             /* This is bogus.  Fix it. */
  1247.             addit = ((unsigned int) ~0) - addit;
  1248.             LFS_STATS_ADD(segPtr->lfsPtr->stats.log.partialFileBytes,
  1249.                 addit);
  1250.         } else {
  1251.             LFS_STATS_ADD(segPtr->lfsPtr->stats.log.partialFileBytes,
  1252.                 segPtr->lfsPtr->stats.log.fileBytesWritten.low -
  1253.                 firstActiveBytesLow);
  1254.         }
  1255.         }
  1256.     }
  1257.    }
  1258.  
  1259.    LfsSetLogTail(segPtr->lfsPtr, &segPtr->logRange, newStartBlockOffset, 
  1260.                 segPtr->activeBytes, segPtr->timeOfLastWrite);  
  1261.    if (segUsageCheckpointRegionPtr != (LfsCheckPointRegion *) NIL) {
  1262.        LfsSegUsageCheckpointUpdate(segPtr->lfsPtr, 
  1263.             (char *) (segUsageCheckpointRegionPtr + 1),
  1264.             segUsageCheckpointRegionPtr->size - 
  1265.                     sizeof(LfsCheckPointRegion));
  1266.     }
  1267.  
  1268.     if (recov_Transparent) {
  1269.     Fsrecov_UpdateLog((int) NIL);
  1270.     }
  1271.     return full;
  1272. }
  1273.  
  1274.  
  1275.  
  1276.  
  1277. /*
  1278.  *----------------------------------------------------------------------
  1279.  *
  1280.  * SegmentCleanProc --
  1281.  *
  1282.  *    Proc_CallFunc procedure for cleaning segments. The routine
  1283.  *    reads the segments into memory by calling the "Clean IN"
  1284.  *    routines and writes the data out by callin the "Clean OUT"
  1285.  *    routines.
  1286.  *
  1287.  * Results:
  1288.  *    None.
  1289.  *
  1290.  * Side effects:
  1291.  *    Segments are mark as clean.    
  1292.  *
  1293.  *----------------------------------------------------------------------
  1294.  */
  1295.  
  1296. /* ARGSUSED */
  1297. static void
  1298. SegmentCleanProc(clientData, callInfoPtr)
  1299.     ClientData      clientData;    /* File system to clean blocks in */
  1300.     Proc_CallInfo *callInfoPtr;         /* Not used. */
  1301.  
  1302. {
  1303.     register Lfs *lfsPtr = (Lfs *) clientData;       
  1304.     int        numSegsToClean, maxNumSegsToClean;
  1305.     LfsSegList    *segs;
  1306.     int        cacheBlocksInUse, segNo, numSegsCleaned, segsGen;
  1307.     LfsSeg     *segPtr;
  1308.     Boolean    full;
  1309.     ReturnStatus    status;
  1310.     ClientData        clientDataArray[LFS_MAX_NUM_MODS];
  1311.     int            numWritten, numCleaned, totalSize, cacheBlocksReserved;
  1312.     int            minNeededToClean, totalNumWritten, maxAvailToWrite;
  1313.     int            totalNumCleaned;
  1314.     Boolean        error;
  1315.     Boolean        checkPoint;
  1316.     char        *memPtr;
  1317.  
  1318. #define    MAX_CLEANING_PASSES    5
  1319. #define    MAX_NUM_SEGS_TO_CLEAN    2048
  1320.  
  1321.  
  1322.  
  1323.     lfsPtr->cleanerProcPtr = Proc_GetCurrentProc();
  1324.     maxNumSegsToClean = lfsPtr->usageArray.checkPoint.numDirty;
  1325.     if (maxNumSegsToClean > MAX_NUM_SEGS_TO_CLEAN) {
  1326.     maxNumSegsToClean = MAX_NUM_SEGS_TO_CLEAN;
  1327.     }
  1328.     segs = (LfsSegList *) malloc(sizeof(LfsSegList) * maxNumSegsToClean);
  1329.     /*
  1330.      * Reserve the memory and cache blocks needed for cleaning.
  1331.      */
  1332.     LfsMemReserve(lfsPtr, &cacheBlocksReserved, &memPtr);
  1333.     numSegsToClean = LfsGetSegsToClean(lfsPtr, maxNumSegsToClean, segs,
  1334.                 &minNeededToClean, &maxAvailToWrite);
  1335.     /*
  1336.      * Loop until the there are less than two segments to clean.
  1337.      */
  1338.     numSegsCleaned = 0;
  1339.     totalNumWritten = totalNumCleaned = 0;
  1340.     while (numSegsToClean > 1) {
  1341.     LFS_STATS_INC(lfsPtr->stats.cleaning.getSegsRequests);
  1342.     LFS_STATS_ADD(lfsPtr->stats.cleaning.segsToClean, numSegsToClean);
  1343.         printf("%s: Cleaning started - deficit %d segs\n", lfsPtr->name,
  1344.             minNeededToClean);
  1345.     if (minNeededToClean < lfsMinNumberToClean) {
  1346.         minNeededToClean = lfsMinNumberToClean;
  1347.     }
  1348.     segNo = 0;
  1349.     segsGen = 0;
  1350.     do {
  1351.         int j;
  1352.         /*
  1353.          * Reading in segments to clean.
  1354.          */
  1355.         for (j = 0; j < LFS_MAX_NUM_MODS; j++) {
  1356.         clientDataArray[j] = (ClientData) NIL;
  1357.         }
  1358.         totalSize = 0;      /* Total size in bytes of data cleaned. */
  1359.         cacheBlocksInUse = 0; /* Number of cache blocks in use. */
  1360.         numCleaned = 0;
  1361.         for (; segNo < numSegsToClean; segNo++) {
  1362.         int size, numCacheBlocksUsed, bytesGenerated;
  1363.         /*
  1364.          * If this segment will no fit in the space reserved in the
  1365.          * cache then end cleaning. Also end cleaning if we 
  1366.          * used up all the segments that we can write. Also end
  1367.          * cleaning if we have someone waiting for us and 
  1368.          * we have generated enough to let them proceed.
  1369.          */
  1370.         bytesGenerated = numCleaned * LfsSegSize(lfsPtr) - totalSize;
  1371.         if ((cacheBlocksInUse + segs[segNo].activeBytes/FS_BLOCK_SIZE >
  1372.                             cacheBlocksReserved) ||
  1373.            ((totalSize + segs[segNo].activeBytes) > 
  1374.                 LfsSegSize(lfsPtr)*maxAvailToWrite) ||
  1375.            (((lfsPtr->activeFlags & LFS_CHECKPOINTWAIT_ACTIVE) ||
  1376.              lfsPtr->writeBackActive) &&
  1377.             (bytesGenerated > LfsSegSize(lfsPtr)*minNeededToClean))
  1378.               ) {
  1379.             break;
  1380.         }
  1381.         size = 0;
  1382.         numCacheBlocksUsed = 0;
  1383. #ifdef ERROR_CHECK
  1384.         if (TRUE) {
  1385. #else
  1386.         if (segs[segNo].activeBytes > 0) { 
  1387. #endif /* ERROR_CHECK */
  1388.             segPtr = CreateSegmentToClean(lfsPtr, segs[segNo].segNumber,
  1389.                 memPtr);
  1390.             error = DoInCallBacks(SEG_CLEAN_IN, segPtr, 0, &size,
  1391.                     &numCacheBlocksUsed, clientDataArray);
  1392.             if (!error && (segs[segNo].activeBytes == 0) && (size != 0)) {
  1393.             printf("Warning: Segment %d cleaned found wrong active bytes %d != %d\n", segs[segNo].segNumber, size, segs[segNo].activeBytes);
  1394.             }
  1395.             DestorySegStruct(segPtr);
  1396.         } else {
  1397.             error = FALSE;
  1398.             size = 0;
  1399.         }
  1400.         if (error) {
  1401.             LFS_STATS_ADD(lfsPtr->stats.cleaning.readErrors, 1);
  1402.             segs[segNo].segNumber = -1;
  1403.         } else { 
  1404.             if (size == 0) {
  1405.             LFS_STATS_INC(lfsPtr->stats.cleaning.readEmpty);
  1406.             } else {
  1407.             int bucket = (size*LFS_STATS_CDIST_BUCKETS)
  1408.                         / LfsSegSize(lfsPtr);
  1409.             if (bucket >= LFS_STATS_CDIST_BUCKETS) {
  1410.                 bucket = (LFS_STATS_CDIST_BUCKETS - 1);
  1411.             }
  1412.             lfsPtr->stats.cleaningDist[bucket]++;
  1413.             }
  1414.             numCleaned++;
  1415.         }
  1416.         totalSize += size;
  1417.         cacheBlocksInUse += numCacheBlocksUsed;
  1418.         }
  1419.         numSegsCleaned = segNo;
  1420.         LFS_STATS_ADD(lfsPtr->stats.cleaning.segReads,numCleaned);
  1421.         LFS_STATS_ADD(lfsPtr->stats.cleaning.bytesCleaned,totalSize);
  1422.         LFS_STATS_ADD(lfsPtr->stats.cleaning.cacheBlocksUsed, cacheBlocksInUse);
  1423.         /*
  1424.          * Write out segments cleaned.
  1425.          */
  1426.         numWritten = 0;
  1427.         if (totalSize > 0) { 
  1428.         full = TRUE;
  1429.         while (full) {
  1430.             segPtr = CreateSegmentToWrite(lfsPtr, TRUE);
  1431.             if (segPtr == (LfsSeg *) NIL) {
  1432.             LfsError(lfsPtr, FAILURE, "Ran out of clean segments during cleaning.\n");
  1433.             }
  1434.             full = DoOutCallBacks(SEG_CLEAN_OUT, segPtr, 
  1435.                     LFS_CLEANING_LAYOUT, (char *) NIL,
  1436.                     (int *) NIL, clientDataArray);
  1437.     
  1438.             status = WriteSegmentStart(segPtr);
  1439.             if (status == SUCCESS) {
  1440.             status = WriteSegmentFinish(segPtr);
  1441.             }
  1442.             if (status != SUCCESS) {
  1443.             LfsError(lfsPtr, status, "Can't write segment to log\n");
  1444.             }
  1445.             RewindCurPtrs(segPtr);
  1446.             (void) DoInCallBacks(SEG_WRITEDONE, segPtr, LFS_CLEANING_LAYOUT,
  1447.                     (int *) NIL, (int *) NIL,  clientDataArray);
  1448.             WriteDoneNotify(lfsPtr);
  1449.             numWritten++;
  1450.             LFS_STATS_ADD(lfsPtr->stats.cleaning.blocksWritten, 
  1451.                     segPtr->numBlocks);
  1452.             LFS_STATS_ADD(lfsPtr->stats.cleaning.bytesWritten, 
  1453.                     segPtr->activeBytes);
  1454.             LFS_STATS_ADD(lfsPtr->stats.cleaning.segWrites, numWritten);
  1455.             DestorySegStruct(segPtr);
  1456.         }
  1457.         }
  1458.         /*
  1459.          * We keep cleaning segments until we have generated
  1460.          * enough segments to get us above a certain threashold.
  1461.          * Becareful not to use all available segments. In more
  1462.          * detail, loop while:
  1463.          * 1) We haven't generated enough segments already.
  1464.          * 2) We haven't cleaned all the segments we are given.
  1465.          * 3) We haven't written out as many segments as possible.
  1466.          * 4) If someone is waiting for us we have cleaned the 
  1467.          *    minimum possible to allow them to proceed.
  1468.          */
  1469.         segsGen += (numCleaned - numWritten);
  1470.         totalNumWritten += numWritten;
  1471.         totalNumCleaned += numCleaned;
  1472.     } while ((segsGen <= minNeededToClean) && (segNo < numSegsToClean) &&
  1473.          (totalNumWritten < maxAvailToWrite) &&
  1474.           !((lfsPtr->activeFlags & LFS_CHECKPOINTWAIT_ACTIVE) &&
  1475.             (segsGen >= lfsMinNumberToClean)));
  1476.  
  1477.     status = LfsCheckPointFileSystem(lfsPtr, 
  1478.             LFS_CHECKPOINT_NOSEG_WAIT|LFS_CHECKPOINT_CLEANER);
  1479.     if (status != SUCCESS) {
  1480.         LfsError(lfsPtr, status, "Can't checkpoint after cleaning.\n");
  1481.     }
  1482.     if (numSegsCleaned > 0) { 
  1483.         lfsPtr->segCache.valid = FALSE;
  1484. #ifdef VERIFY_CLEAN
  1485.         { 
  1486.         int i;
  1487.  
  1488.          for (i = 0; i < numSegsCleaned; i++) {
  1489.             int size, numCacheBlocksUsed;
  1490.             /*
  1491.              * If a segment couldn't be cleaned then its segment
  1492.              * number is set to -1. Just skip these.
  1493.              */
  1494.             if (segs[i].segNumber == -1) {
  1495.             continue;
  1496.             }
  1497.             segPtr = CreateSegmentToClean(lfsPtr, segs[i].segNumber,
  1498.                 memPtr);
  1499.             error = DoInCallBacks(SEG_CLEAN_VERIFY, segPtr, 0, &size,
  1500.                     &numCacheBlocksUsed, clientDataArray);
  1501.             DestorySegStruct(segPtr);
  1502.         }
  1503.         }
  1504. #endif
  1505.         LfsMarkSegsClean(lfsPtr, numSegsCleaned, segs);
  1506.         LOCK_MONITOR;
  1507.         lfsPtr->activeFlags &= ~LFS_CLEANSEGWAIT_ACTIVE;
  1508.         Sync_Broadcast(&lfsPtr->cleanSegmentsWait);
  1509.         UNLOCK_MONITOR;
  1510.     }
  1511.     printf("%s: Cleaned %d segments in %d segments\n", 
  1512.             lfsPtr->name, totalNumCleaned, totalNumWritten);
  1513.     numSegsToClean = LfsGetSegsToClean(lfsPtr, maxNumSegsToClean, segs,
  1514.              &minNeededToClean, &maxAvailToWrite);
  1515.     if (minNeededToClean == 0) {
  1516.         break;
  1517.     }
  1518.     }
  1519.     free((char *)segs);
  1520.     lfsPtr->segCache.valid = FALSE;
  1521.     LfsMemRelease(lfsPtr, cacheBlocksReserved, memPtr);
  1522.  
  1523.     LOCK_MONITOR;
  1524.     /*  
  1525.      * Release the flags that mark us as an active cleaner process for
  1526.      * this file system.
  1527.      * If someone is waiting for us to checkpoint.
  1528.      */
  1529.     lfsPtr->activeFlags &= ~LFS_CLEANER_ACTIVE;
  1530.     lfsPtr->cleanerProcPtr = (Proc_ControlBlock *) NIL;
  1531.     checkPoint = (lfsPtr->activeFlags & LFS_CHECKPOINTWAIT_ACTIVE);
  1532.     UNLOCK_MONITOR;
  1533.  
  1534.     if (checkPoint) { 
  1535.     (void) LfsCheckPointFileSystem(lfsPtr, 0);
  1536.     }
  1537.  
  1538. }
  1539.  
  1540.  
  1541. static LfsSeg *
  1542. CreateSegmentToClean(lfsPtr, segNumber, cleaningMemPtr)
  1543.     Lfs    *lfsPtr;    /* File system of segment. */
  1544.     int    segNumber;    /* Segment number to clean. */
  1545.     char *cleaningMemPtr; /* Memory to use for cleaning. */
  1546. {
  1547.     LfsSeg        *segPtr;
  1548.     int            segSize;
  1549.     ReturnStatus    status;
  1550.     LfsSegLogRange    logRange;
  1551.     LfsSegSummary    *segSumPtr;
  1552.     LfsSegSummary    *prevSegSumPtr;
  1553.     LfsDiskAddr        diskAddress;
  1554.     int            blocksPerSeg;
  1555.  
  1556.     logRange.prevSeg = -1;
  1557.     logRange.current = segNumber;
  1558.     logRange.nextSeg = -1;
  1559.  
  1560.     /*
  1561.      * Get a LfsSeg structure.
  1562.      */
  1563.     lfsPtr->segCache.valid = FALSE;
  1564.     segPtr = GetSegStruct(lfsPtr, &logRange, 0, cleaningMemPtr);
  1565.  
  1566.     /*
  1567.      * Read in the segment in memory.
  1568.      */
  1569.     segSize = LfsSegSize(lfsPtr);
  1570.     blocksPerSeg = LfsBytesToBlocks(lfsPtr,segSize);
  1571.     LfsSegNumToDiskAddress(lfsPtr, segNumber, &diskAddress);
  1572.     status = LfsReadBytes(lfsPtr, diskAddress, segSize, cleaningMemPtr);
  1573.     if (status != SUCCESS) {
  1574.     LfsError(lfsPtr, status, "Can't read segment to clean.\n");
  1575.     return (LfsSeg *) NIL;
  1576.     }
  1577.     lfsPtr->segCache.segNum = segNumber;
  1578.     LfsSegNumToDiskAddress(lfsPtr, segNumber, 
  1579.         &lfsPtr->segCache.startDiskAddress);
  1580.     LfsSegNumToDiskAddress(lfsPtr, segNumber+1, 
  1581.         &lfsPtr->segCache.endDiskAddress);
  1582.     lfsPtr->segCache.memPtr = cleaningMemPtr;
  1583.     lfsPtr->segCache.valid = TRUE;
  1584.  
  1585.     segSumPtr = (LfsSegSummary *)
  1586.         (cleaningMemPtr + segSize - LfsBlockSize(lfsPtr));
  1587.     prevSegSumPtr = segSumPtr;
  1588.     while (1) { 
  1589.     if (segSumPtr->magic != LFS_SEG_SUMMARY_MAGIC) {
  1590.         printf("Bad segment summary magic in segment %d\n", segNumber);
  1591.         if (segSumPtr == prevSegSumPtr) {
  1592.         LfsError(lfsPtr, FAILURE,
  1593.              "Corrupted summary block at start of segment\n");
  1594.         panic("Previous error not continuable.\n");
  1595.         } else {
  1596.         LfsError(lfsPtr, FAILURE,
  1597.              "Corrupted segment summary block (continuable)\n");
  1598.         prevSegSumPtr->nextSummaryBlock = -1;
  1599.         break;
  1600.         }
  1601.     }
  1602.     segPtr->segElementPtr[segPtr->numElements].lengthInBlocks = 0;
  1603.     segPtr->segElementPtr[segPtr->numElements].address = (char *) segSumPtr;
  1604.     segPtr->segElementPtr[segPtr->numElements].clientData = 
  1605.                 (ClientData) NIL;
  1606.     segPtr->numElements++;
  1607.  
  1608.     LFS_STATS_INC(lfsPtr->stats.cleaning.summaryBlocksRead);
  1609.     if (segSumPtr->nextSummaryBlock == -1) {
  1610.         break;
  1611.     }
  1612.     if (segPtr->numElements > blocksPerSeg) {
  1613.         printf("Lfs: Bad segment %d\n", segNumber);
  1614.         LfsError(lfsPtr, FAILURE, "Corrupted segment\n");
  1615.     }
  1616.     if ((segSumPtr->nextSummaryBlock < 0) || 
  1617.         (segSumPtr->nextSummaryBlock > blocksPerSeg)) {
  1618.         printf("Bogus next pointer in segment summary block %d\n",
  1619.            segNumber);
  1620.         LfsError(lfsPtr, FAILURE,
  1621.              "Corrupted segment summary block (continuable)\n");
  1622.         segSumPtr->nextSummaryBlock = -1;
  1623.         break;
  1624.     }
  1625.     prevSegSumPtr = segSumPtr;
  1626.     segSumPtr = (LfsSegSummary *) 
  1627.             LfsSegFetchBytes(segPtr, segSumPtr->nextSummaryBlock,
  1628.                 LfsBlockSize(lfsPtr));
  1629.     }
  1630.     RewindCurPtrs(segPtr);
  1631.     return segPtr;
  1632. }
  1633.  
  1634. /*
  1635.  *----------------------------------------------------------------------
  1636.  *
  1637.  * LfsSegAttach --
  1638.  *
  1639.  *    Call the attach routines all the segment I/O modules.
  1640.  *
  1641.  * Results:
  1642.  *    SUCCESS if everything when well.
  1643.  *
  1644.  * Side effects:
  1645.  *    None.
  1646.  *
  1647.  *----------------------------------------------------------------------
  1648.  */
  1649.  
  1650. ReturnStatus
  1651. LfsSegAttach(lfsPtr, checkPointPtr, checkPointSize)
  1652.     Lfs        *lfsPtr;    /* File system being attached. */
  1653.     char        *checkPointPtr; /* Latest checkpoint header. */
  1654.     int        checkPointSize; /* Size of the checkpoint buffer. */
  1655. {
  1656.     int        moduleType;
  1657.     char    *limitPtr;
  1658.     LfsCheckPointRegion *regionPtr;
  1659.     ReturnStatus    status;
  1660.     LfsSegIoInterface    *segIoPtr;
  1661.  
  1662.     lfsPtr->segCache.valid = FALSE;
  1663.  
  1664.     limitPtr = checkPointPtr + checkPointSize;
  1665.     for (moduleType = 0; moduleType < LFS_MAX_NUM_MODS; moduleType++) {
  1666.     regionPtr = (LfsCheckPointRegion *) checkPointPtr;
  1667.     segIoPtr = lfsSegIoInterfacePtrs[moduleType];
  1668.     if ((checkPointPtr < limitPtr) && (regionPtr->type == moduleType)) { 
  1669.         checkPointPtr += regionPtr->size;
  1670.         status = segIoPtr->attach(lfsPtr, 
  1671.                 (int)(regionPtr->size - sizeof(*regionPtr)),
  1672.                 (char *) (regionPtr+1));
  1673. #ifdef lint
  1674.         status = LfsDescMapAttach(lfsPtr, 
  1675.                 (int)(regionPtr->size - sizeof(*regionPtr)),
  1676.                 (char *) (regionPtr+1));
  1677.         status = LfsFileLayoutAttach(lfsPtr, 
  1678.                 (int)(regionPtr->size - sizeof(*regionPtr)),
  1679.                 (char *) (regionPtr+1));
  1680.         status = LfsSegUsageAttach(lfsPtr, 
  1681.                 (int)(regionPtr->size - sizeof(*regionPtr)),
  1682.                 (char *) (regionPtr+1));
  1683.  
  1684. #endif /* lint */
  1685.     } else {
  1686.         status = segIoPtr->attach(lfsPtr, 0, (char *)NIL);
  1687. #ifdef lint
  1688.         status = LfsDescMapAttach(lfsPtr, 0, (char *)NIL);
  1689.         status = LfsFileLayoutAttach(lfsPtr, 0, (char *)NIL);
  1690.         status = LfsSegUsageAttach(lfsPtr, 0, (char *)NIL);
  1691. #endif /* lint */
  1692.     }
  1693.     if (status != SUCCESS) {
  1694.         LfsError(lfsPtr, status, "Can't attach module");
  1695.         break;
  1696.     }
  1697.     }
  1698.     if (status == SUCCESS) {
  1699.     InitSegmentMem(lfsPtr);
  1700.     return status;
  1701.     }
  1702.     /*
  1703.      * XXX - Back out of error here by shutting down all module.
  1704.      */
  1705.     return status;
  1706. }
  1707.  
  1708. /*
  1709.  *----------------------------------------------------------------------
  1710.  *
  1711.  * LfsSegCheckPoint --
  1712.  *
  1713.  *    Call the checkpoint routines all the segment I/O modules.
  1714.  *
  1715.  * Results:
  1716.  *    SUCCESS if everything when well.
  1717.  *
  1718.  * Side effects:
  1719.  *    None.
  1720.  *
  1721.  *----------------------------------------------------------------------
  1722.  */
  1723.  
  1724. ReturnStatus
  1725. LfsSegCheckPoint(lfsPtr, flags, checkPointPtr, checkPointSizePtr)
  1726.     Lfs              *lfsPtr;        /* File system to checkpoint. */
  1727.     int            flags;        /* Flags to checkpoint operation. */
  1728.     char        *checkPointPtr;    /* Checkpoint area to be filled in.*/
  1729.     int            *checkPointSizePtr; /* Size of checkpoint buffer. */
  1730. {
  1731.     Boolean    full = TRUE;
  1732.     LfsSeg    *segPtr;
  1733.     ClientData        clientDataArray[LFS_MAX_NUM_MODS];
  1734.     int            i;
  1735.     ReturnStatus    status= SUCCESS;
  1736.  
  1737.     LOCK_MONITOR;
  1738.  
  1739.     /*
  1740.      * Wait for the cleaner not to be active unless we are called from the 
  1741.      * cleaner, the detach code, or the timer callback.
  1742.      */
  1743.     if (lfsPtr->activeFlags & LFS_CLEANER_ACTIVE) {
  1744.     if (flags & LFS_CHECKPOINT_TIMER) {
  1745.         /*
  1746.          * Since the cleaner does checkpoints frequently, we can safely
  1747.          * ignore TIMER checkpoints.
  1748.          */
  1749.         (*checkPointSizePtr) = -1;
  1750.         UNLOCK_MONITOR;
  1751.         return SUCCESS;
  1752.         }
  1753.     if (!(flags & (LFS_CHECKPOINT_DETACH|LFS_CHECKPOINT_CLEANER))) {
  1754.         /*
  1755.          * Unless the checkpoint is from the cleaner or the detach 
  1756.          * code we simply wait for a checkpoint to complete and 
  1757.          * return.
  1758.          */
  1759.         if (!(lfsPtr->activeFlags & LFS_CHECKPOINTWAIT_ACTIVE)) {
  1760.         lfsPtr->activeFlags |= LFS_CHECKPOINTWAIT_ACTIVE;
  1761.         }
  1762.         while (lfsPtr->activeFlags & LFS_CHECKPOINTWAIT_ACTIVE) { 
  1763.         Sync_Wait(&lfsPtr->checkPointWait, FALSE);
  1764.         }
  1765.         (*checkPointSizePtr) = -1;
  1766.         UNLOCK_MONITOR;
  1767.         return SUCCESS;
  1768.     } 
  1769.     }
  1770.     /*
  1771.      * Wait for any currently running checkpoint to finish.
  1772.      * TIMER checkpoints again can be ignored and cleaner checkpoint can
  1773.      * run in parallel.
  1774.      */
  1775.     if (!(flags & LFS_CHECKPOINT_CLEANER)) { 
  1776.     while (lfsPtr->activeFlags & LFS_CHECKPOINT_ACTIVE) {
  1777.         if (flags & LFS_CHECKPOINT_TIMER) {
  1778.         (*checkPointSizePtr) = -1;
  1779.         UNLOCK_MONITOR;
  1780.         return SUCCESS;
  1781.         }
  1782.         Sync_Wait(&lfsPtr->checkPointWait, FALSE);
  1783.     }
  1784.     lfsPtr->activeFlags |= LFS_SYNC_CHECKPOINT_ACTIVE;
  1785.     } else {
  1786.     lfsPtr->activeFlags |= LFS_CLEANER_CHECKPOINT_ACTIVE;
  1787.     }
  1788.  
  1789.     /*
  1790.      * Wait for any directory log operations to finish.
  1791.      */
  1792.     while (lfsPtr->dirModsActive > 0) {
  1793.     Sync_Wait(&lfsPtr->checkPointWait, FALSE);
  1794.     }
  1795.     /*
  1796.      * If we a detatching the file system wait for any cleaners to exit.
  1797.      */
  1798.     if (flags & LFS_CHECKPOINT_DETACH) {
  1799.     lfsPtr->activeFlags |= LFS_SHUTDOWN_ACTIVE;
  1800.     while (lfsPtr->activeFlags & LFS_CLEANER_ACTIVE) {
  1801.         Time time;
  1802.         time.seconds = 1;
  1803.         time.microseconds = 0;
  1804.         Sync_WaitTime(time);
  1805.     }
  1806.     }
  1807.     LFS_STATS_INC(lfsPtr->stats.checkpoint.count);
  1808.     UNLOCK_MONITOR;
  1809.  
  1810.     if (flags & LFS_CHECKPOINT_DETACH) {
  1811.     LfsStopWriteBack(lfsPtr);
  1812.     }
  1813.  
  1814.     for (i = 0; i < LFS_MAX_NUM_MODS; i++) {
  1815.     clientDataArray[i] = (ClientData) NIL;
  1816.     }
  1817.     while (full) {
  1818.     segPtr = CreateSegmentToWrite(lfsPtr, 
  1819.             ((flags & LFS_CHECKPOINT_NOSEG_WAIT) != 0));
  1820.     if (segPtr == (LfsSeg *) NIL) {
  1821.         LfsError(lfsPtr, FAILURE, "Ran out of clean segments during cleaner checkpoint.\n");
  1822.     }
  1823.     *checkPointSizePtr = 0;
  1824.     full = DoOutCallBacks(SEG_CHECKPOINT, segPtr, flags,
  1825.                 checkPointPtr, checkPointSizePtr, clientDataArray);
  1826.     LFS_STATS_INC(lfsPtr->stats.checkpoint.segWrites);
  1827.     LFS_STATS_ADD(lfsPtr->stats.checkpoint.blocksWritten,
  1828.                     segPtr->numBlocks);
  1829.     LFS_STATS_ADD(lfsPtr->stats.checkpoint.bytesWritten,
  1830.                 segPtr->activeBytes);
  1831.     status = WriteSegmentStart(segPtr);
  1832.     if (status == SUCCESS) {
  1833.         status = WriteSegmentFinish(segPtr);
  1834.     }
  1835.     if (status != SUCCESS) {
  1836.         LfsError(lfsPtr, status, "Can't write segment to log\n");
  1837.     }
  1838.     RewindCurPtrs(segPtr);
  1839.     (void) DoInCallBacks(SEG_WRITEDONE, segPtr, flags, (int *) NIL, (int *) NIL,
  1840.                 clientDataArray);
  1841.     WriteDoneNotify(lfsPtr);
  1842.         DestorySegStruct(segPtr);
  1843.     }
  1844.     return status;
  1845.  
  1846. }
  1847.  
  1848. /*
  1849.  *----------------------------------------------------------------------
  1850.  *
  1851.  * LfsSegCheckPointDone --
  1852.  *
  1853.  *    Mark a checkpoint as done.
  1854.  *
  1855.  * Results:
  1856.  *    None.
  1857.  *
  1858.  * Side effects:
  1859.  *    None.
  1860.  *
  1861.  *----------------------------------------------------------------------
  1862.  */
  1863.  
  1864. void
  1865. LfsSegCheckPointDone(lfsPtr, flags)
  1866.     Lfs    *lfsPtr;
  1867.     int    flags;
  1868. {
  1869.     LOCK_MONITOR;
  1870.     lfsPtr->numDirtyBlocks = 0;
  1871. #ifdef notdef
  1872.     { 
  1873.     int numBlocks, numDirty;
  1874.     Fscache_CountBlocks(rpc_SpriteID, lfsPtr->domainPtr->domainNumber,
  1875.                 &numBlocks, &numDirty);
  1876.     if (((flags & LFS_CHECKPOINT_DETACH) && numDirty) || (numDirty > 1)) {
  1877.         printf("DirtyBlocks (%d) after a checkpoint\n", numDirty);
  1878.     }
  1879.     }
  1880. #endif
  1881.     if (flags & LFS_CHECKPOINT_CLEANER) {
  1882.     lfsPtr->activeFlags &= 
  1883.         ~(LFS_CLEANER_CHECKPOINT_ACTIVE|LFS_CHECKPOINTWAIT_ACTIVE|
  1884.           LFS_CLEANSEGWAIT_ACTIVE);
  1885.     Sync_Broadcast(&lfsPtr->cleanSegmentsWait)
  1886.     } else { 
  1887.     lfsPtr->activeFlags &= 
  1888.         ~(LFS_SYNC_CHECKPOINT_ACTIVE|LFS_CHECKPOINTWAIT_ACTIVE);
  1889.     }
  1890.     Sync_Broadcast(&lfsPtr->checkPointWait);
  1891.     UNLOCK_MONITOR;
  1892. }
  1893.  
  1894. /*
  1895.  *----------------------------------------------------------------------
  1896.  *
  1897.  * LfsSegDetach --
  1898.  *
  1899.  *    Call a shutdown time on an LFS file system.
  1900.  *
  1901.  * Results:
  1902.  *    SUCCESS if everything when well.
  1903.  *
  1904.  * Side effects:
  1905.  *    None.
  1906.  *
  1907.  *----------------------------------------------------------------------
  1908.  */
  1909.  
  1910. ReturnStatus
  1911. LfsSegDetach(lfsPtr)
  1912.     Lfs              *lfsPtr;        /* File system to checkpoint. */
  1913. {
  1914.  
  1915.     int    moduleType;
  1916.     LfsSegIoInterface    *segIoPtr;
  1917.     ReturnStatus status = SUCCESS;
  1918.  
  1919.     for (moduleType = 0; moduleType < LFS_MAX_NUM_MODS; moduleType++) {
  1920.     segIoPtr = lfsSegIoInterfacePtrs[moduleType];
  1921.     status = segIoPtr->detach(lfsPtr);
  1922. #ifdef lint
  1923.     status = LfsDescMapDetach(lfsPtr);
  1924.     status = LfsFileLayoutDetach(lfsPtr);
  1925.     status = LfsSegUsageDetach(lfsPtr);
  1926. #endif 
  1927.     }
  1928.     FreeSegmentMem(lfsPtr);
  1929.     return status;
  1930.  
  1931. }
  1932.  
  1933. /*
  1934.  *----------------------------------------------------------------------
  1935.  *
  1936.  * LfsWaitForCheckPoint --
  1937.  *
  1938.  *    Wait for a checkpoint to complete on a file system.
  1939.  *
  1940.  * Results:
  1941.  *    None.
  1942.  *
  1943.  * Side effects:
  1944.  *    None.
  1945.  *
  1946.  *----------------------------------------------------------------------
  1947.  */
  1948. void
  1949. LfsWaitForCheckPoint(lfsPtr) 
  1950.     Lfs    *lfsPtr;
  1951. {
  1952.     LOCK_MONITOR;
  1953.     while (lfsPtr->activeFlags & LFS_CHECKPOINT_ACTIVE) {
  1954.     Sync_Wait(&lfsPtr->checkPointWait, FALSE);
  1955.     }
  1956.     UNLOCK_MONITOR;
  1957. }
  1958.  
  1959. /*
  1960.  *----------------------------------------------------------------------
  1961.  *
  1962.  * LfsWaitForCleanSegments --
  1963.  *
  1964.  *    Ensure that there is enough clean segments to write a
  1965.  *    dirty cache block being added to the system. Also
  1966.  *    besure that a checkpoint is not active.
  1967.  *
  1968.  * Results:
  1969.  *    None.
  1970.  *
  1971.  * Side effects:
  1972.  *    None.
  1973.  *
  1974.  *----------------------------------------------------------------------
  1975.  */
  1976.  
  1977.  
  1978. void
  1979. LfsWaitForCleanSegments(lfsPtr)
  1980.     Lfs    *lfsPtr;
  1981. {
  1982.     LOCK_MONITOR;
  1983.     lfsPtr->numDirtyBlocks++;
  1984.     while ((lfsPtr->activeFlags & LFS_CHECKPOINT_ACTIVE) ||
  1985.         !LfsSegUsageEnoughClean(lfsPtr, 
  1986.             lfsPtr->numDirtyBlocks * FS_BLOCK_SIZE)) {
  1987.     if (!(lfsPtr->activeFlags & LFS_CHECKPOINTWAIT_ACTIVE)) {
  1988.         lfsPtr->activeFlags |= LFS_CHECKPOINTWAIT_ACTIVE;
  1989.     }
  1990.     Sync_Wait(&lfsPtr->checkPointWait, FALSE);
  1991.     }
  1992.     UNLOCK_MONITOR;
  1993. }
  1994.  
  1995.